﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using WF_ExportTool.Common;
using WF_ExportTool.Configuration.Auto;
using WF_ExportTool.Configuration.DataV;
using WF_ExportTool.Configuration.Form;
using WF_ExportTool.Configuration.Grid;
using WF_ExportTool.Configuration.Tab;
using WF_ExportTool.Configuration.Tree;
using static WF_ExportTool.Common.CommonEnum;

namespace WF_ExportTool.Configuration
{
    /// <summary>
    ///列表数据操作
    /// </summary>
    public class CommonEngine
    {
        DbHelper dbHelper = new DbHelper();

        #region  列表
        /// <summary>
        /// 返回列表主表信息
        /// </summary>
        /// <param name="DbIns">数据库链接实例</param>
        /// <param name="parameter">参数，查询条件</param>
        /// <returns></returns>
        public IList<Grid_Main> ReadGrid_MainForDbIns(string parameter)
        {
            IList<Grid_Main> GridmainList =new List<Grid_Main>();
            //获取主数据
            string sql = "select * from Grid_Main where  {0}";
            DataTable mainData = dbHelper.ExecuteDataTable(string.Format(sql,  parameter));
            if (mainData == null) return null;
            // 把DataTable转换为IList<GridmainList>  
            ModelConvertHelper modelHelper = new ModelConvertHelper();
            GridmainList = modelHelper.ConvertToModelByGridMain(mainData);
            return GridmainList;
        }

        /// <summary>
        /// 导出列表数据
        /// </summary>
        /// <param name="GridCodeItems">GridCode集合</param>
        /// <returns></returns>
        public IList<Dictionary<string, string>> ExportGridData(string[] GridCodeItems)
        {
            IList<Dictionary<string, string>> exprotContent = new List<Dictionary<string, string>>();
            if (GridCodeItems.Length > 0)
            {
                string gridCode = "";
                foreach (string s in GridCodeItems)
                {
                    gridCode += "'" + s.ToString() + "',";
                }
                gridCode = gridCode.Trim(',');
                ModelConvertHelper modelHelper = new ModelConvertHelper();
                IList<Dictionary<string, string>> dicGridMain = new List<Dictionary<string, string>>();
                IList<Dictionary<string, string>> dicGridColumn = new List<Dictionary<string, string>>();

                //获取主数据
                string sql = "select * from Grid_Main where GridCode in ({0})";
                DataTable mainData = dbHelper.ExecuteDataTable(string.Format(sql, gridCode));
                if (mainData == null) return null;
                // 把DataTable转换为IList<GridmainList>  
                //GridmainList = modelHelper.ConvertToModelByGridMain(mainData);
                Grid_Main gridMain = new Grid_Main();
                Type type = typeof(Grid_Main);
                dicGridMain = modelHelper.ConvertToDicByDataTable(mainData, gridMain, type);
                string GridMain = this.GridTemplateData(dicGridMain, "Grid_Main", "CPCommon", "GridId");
                foreach (Dictionary<string, string> dicGrid in dicGridMain)
                {
                    IList<Dictionary<string, string>> dicGridCol = new List<Dictionary<string, string>>();
                    string GridId = dicGrid["GridId"];
                    string colsql = "select * from Grid_Column where GridId='{0}'";
                    DataTable columnData = dbHelper.ExecuteDataTable(string.Format(colsql, GridId));
                    if (columnData == null) continue;
                    Grid_Column gridColumn = new Grid_Column();
                    Type types = typeof(Grid_Column);
                    dicGridCol = modelHelper.ConvertToDicByDataTable(columnData, gridColumn, types);
                    foreach (Dictionary<string, string> dicG in dicGridCol) {
                        dicGridColumn.Add(dicG);
                    }
                }
                string GridColumn = this.GridTemplateData(dicGridColumn, "Grid_Column", "CPCommon", "ColumnId");
                string sqlContent = GridMain + "!" + GridColumn;
                string sqlName = "Grid_Main!Grid_Column";
                //this.SaveFileSQL(sqlContent,sqlName);
                Dictionary<string, string> dic1 = new Dictionary<string, string>();
                dic1.Add("content", GridMain.ToString());
                dic1.Add("name", "Grid_Main");
                Dictionary<string, string> dic2 = new Dictionary<string, string>();
                dic2.Add("content", GridColumn.ToString());
                dic2.Add("name", "Grid_Column");
                exprotContent.Add(dic1);
                exprotContent.Add(dic2);
            }
            return exprotContent;
        }

        #endregion

        #region 表单
        /// <summary>
        /// 返回查询表单数据源
        /// </summary>
        /// <param name="DbIns"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public IList<Form_Main> ReadForm_MainForDbIns( string parameter)
        {
            IList<Form_Main> FormmainList = new List<Form_Main>();
            //获取主数据
            string sql = "select * from Form_Main where {0}";
            DataTable mainData = dbHelper.ExecuteDataTable(string.Format(sql,  parameter));
            if (mainData == null) return null;
            // 把DataTable转换为IList<GridmainList>  
            ModelConvertHelper modelHelper = new ModelConvertHelper();
            Type type = typeof(Form_Main);
            Form_Main t = new Form_Main();
            FormmainList = modelHelper.ConvertToModelByFormMain(mainData);
            return FormmainList;
        }
        #endregion


        #region 自动编号工具
        /// <summary>
        /// 返回查询自动编号数据源
        /// </summary>
        /// <param name="DbIns"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public IList<CP_AutoNum> ReadAuto_MainForDbIns( string parameter)
        {
            IList<CP_AutoNum> AutomainList = new List<CP_AutoNum>();
            //获取主数据
            string sql = "select * from CP_AutoNum where {0}";
            DataTable mainData = dbHelper.ExecuteDataTable(string.Format(sql,  parameter));
            if (mainData == null) return null;
            // 把DataTable转换为IList<GridmainList>  
            ModelConvertHelper modelHelper = new ModelConvertHelper();
            AutomainList =modelHelper.ConvertToModelByAutoMain(mainData);
            return AutomainList;
        }
        #endregion


        #region 标签页工具
        /// <summary>
        /// 返回查询标签页数据源
        /// </summary>
        /// <param name="DbIns"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public IList<Tab_Main> ReadTab_MainForDbIns( string parameter)
        {
            IList<Tab_Main> TabmainList = new List<Tab_Main>();
            //获取主数据
            string sql = "select * from Tab_Main where  {0}";
            DataTable mainData = dbHelper.ExecuteDataTable(string.Format(sql, parameter));
            if (mainData == null) return null;
            // 把DataTable转换为IList<GridmainList>  
            ModelConvertHelper modelHelper = new ModelConvertHelper();
            TabmainList = modelHelper.ConvertToModelByTabMain(mainData);
            return TabmainList;
        }
        #endregion

        #region 树工具
        /// <summary>
        /// 返回查询树工具数据源
        /// </summary>
        /// <param name="DbIns"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public IList<Tree_Main> ReadTree_MainForDbIns(string parameter)
        {
            IList<Tree_Main> TreemainList = new List<Tree_Main>();
            //获取主数据
            string sql = "select * from Tree_Main where {0}";
            DataTable mainData = dbHelper.ExecuteDataTable(string.Format(sql, parameter));
            if (mainData == null) return null;
            // 把DataTable转换为IList<GridmainList>  
            ModelConvertHelper modelHelper = new ModelConvertHelper();
            TreemainList = modelHelper.ConvertToModelByTreeMain(mainData);
            return TreemainList;
        }
        #endregion

        #region 数据统计（图表）
        /// <summary>
        /// 返回查询数据统计（图表）数据源
        /// </summary>
        /// <param name="DbIns"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public IList<DataV_Main> ReadDataV_MainForDbIns(string parameter)
        {
            IList<DataV_Main> DataVmainList = new List<DataV_Main>();
            //获取主数据
            string sql = "select * from DataV_Main where {0}";
            DataTable mainData = dbHelper.ExecuteDataTable(string.Format(sql, parameter));
            if (mainData == null) return null;
            // 把DataTable转换为IList<GridmainList>  
            ModelConvertHelper modelHelper = new ModelConvertHelper();
            DataVmainList = modelHelper.ConvertToModelByDataVMain(mainData);
            return DataVmainList;
        }
        #endregion

        /// <summary>
        /// 获取需要导出的数据
        /// </summary>
        /// <param name="CodeItems"></param>
        /// <returns>格式：content：一个表的temp；name：表名称</returns>
        public IList<Dictionary<string, string>> ExportData(string[] CodeItems,string configname)
        {
            IList<Dictionary<string, string>> exprotContent = new List<Dictionary<string, string>>();
            if (CodeItems.Length > 0)
            {
                string Code = "";
                foreach (string s in CodeItems)
                {
                    Code += "'" + s.ToString() + "',";
                }
                Code = Code.Trim(',');
                ModelConvertHelper modelHelper = new ModelConvertHelper();
                IList<Dictionary<string, string>> dicMain = new List<Dictionary<string, string>>();
                IList<Dictionary<string, string>> dicAssist = new List<Dictionary<string, string>>();
                ExportDataConfiguration services = ExportDataConfiguration.GetConfig(configname);
                foreach (TheKeyValue item in services.KeyValues)
                {
                    var i = item.IsMainTable;string mainfield = item.MainField, tablename = item.TableName, fieldname = item.FieldName;
                    string sql = "select * from {0} where {1} in ({2})";
                    if (i == "1")
                    {
                        sql = string.Format(sql, tablename, fieldname, Code);
                        DataTable mainData = dbHelper.ExecuteDataTable(sql);
                        BaseEntity main = this.GetObject(tablename);
                        Type type = typeof(BaseEntity);
                        dicMain = modelHelper.ConvertToDicByDataTable(mainData, main, type);
                        string Main = this.GridTemplateData(dicMain, tablename, "CPCommon", mainfield);
                        Dictionary<string, string> dic1 = new Dictionary<string, string>();
                        dic1.Add("content", Main.ToString());
                        dic1.Add("name", tablename);
                        exprotContent.Add(dic1);
                        Code = "";
                        foreach (DataRow r in mainData.Rows)
                        {
                            Code += "'" + r[mainfield].ToString() + "',";
                        }
                        Code = Code.Trim(',');
                    }
                    else
                    {
                        sql = string.Format(sql, tablename, mainfield, Code);
                        DataTable assistData = dbHelper.ExecuteDataTable(sql);
                        if (assistData.Rows.Count == 0) continue;//数据为空，不导出
                        BaseEntity assist = this.GetObject(tablename);
                        Type type = typeof(BaseEntity);
                        dicAssist = modelHelper.ConvertToDicByDataTable(assistData, assist, type);
                        string Assist = this.GridTemplateData(dicAssist, tablename, "CPCommon", fieldname);
                        Dictionary<string, string> dic2 = new Dictionary<string, string>();
                        dic2.Add("content", Assist.ToString());
                        dic2.Add("name", tablename);
                        exprotContent.Add(dic2);
                    }
                    

                }
            }
            return exprotContent;
        }

        /// <summary>
        /// 根据表名返回实例对象
        /// </summary>
        /// <param name="tablename"></param>
        /// <returns></returns>
        private BaseEntity GetObject(string tablename)
        {
            BaseEntity t = null; 
            switch (tablename)
            {
                case "Grid_Main":
                    t = new Grid_Main();
                    break;
                case "Grid_Column":
                    t = new Grid_Column();
                    break;
                case "Grid_Func":
                    t = new Grid_Func();
                    break;
                case "Form_Main":
                    t = new Form_Main();
                    break;
                case "Form_ChildTable":
                    t = new Form_ChildTable();
                    break;
                case "Form_Field":
                    t = new Form_Field();
                    break;
                case "Form_View":
                    t = new Form_View();
                    break;
                case "Form_View_Inner":
                    t = new Form_View_Inner();
                    break;
                case "Form_UseScene":
                    t = new Form_UseScene();
                    break;
                case "Form_UseSceneFunc":
                    t = new Form_UseSceneFunc();
                    break;
                case "Form_Group":
                    t = new Form_Group();
                    break;
                case "Form_FieldRight":
                    t = new Form_FieldRight();
                    break;
                case "Form_FieldInitValue":
                    t = new Form_FieldInitValue();
                    break;
                case "Tab_Main":
                    t = new Tab_Main();
                    break;
                case "Tab_Element":
                    t = new Tab_Element();
                    break;
                case "Tree_Main":
                    t = new Tree_Main();
                    break;
                case "Tree_DataSource":
                    t = new Tree_DataSource();
                    break;
                case "Tree_Func":
                    t = new Tree_Func();
                    break;
                case "DataV_Main":
                    t = new DataV_Main();
                    break;
                case "DataV_Statistics":
                    t = new DataV_Statistics();
                    break;
                case "DataV_ChartSeries":
                    t = new DataV_ChartSeries();
                    break;
                case "DataV_Layout":
                    t = new DataV_Layout();
                    break;
                case "CP_AutoNum":
                    t = new CP_AutoNum();
                    break;
            }

            return t;
        }

        /// <summary>
        /// 模板数据反馈
        /// </summary>
        /// <param name="GridList">数据源集合</param>
        /// <param name="tableName">数据表</param>
        /// <param name="database">数据库</param>
        /// <param name="PrimaryKey">主键</param>
        private string GridTemplateData(IList<Dictionary<string, string>> GridList,string tableName,string database,string PrimaryKey)
        {
            //按照模板生成insert/update更新数据 
            //
            string tmp = "";
            if (GridList.Count > 0)
            {
                tmp += "USE " + database + System.Environment.NewLine;
                string str = "";
                foreach (Dictionary<string, string> dicGrid in GridList)
                {
                    string str1 = "", str2 = "", str3 = "", str4 = "", priKeyValue = "";
                    foreach (string key in dicGrid.Keys)
                    {
                        if (key == PrimaryKey)
                        {
                            str1 = "IF  NOT EXISTS(SELECT 1 FROM [dbo].[" + tableName + "] WHERE [" + PrimaryKey + "]=" + dicGrid[key] + ")";
                            str2 += key + ",";
                            str3 += "'" + ((dicGrid[key].ToLower().Contains("'")) ? dicGrid[key].Replace("'", "''") : dicGrid[key]) + "',";
                            priKeyValue = dicGrid[key];
                        }
                        else
                        {

                            str2 += key + ",";
                            str3 += "'" + ((dicGrid[key].ToLower().Contains("'")) ? dicGrid[key].Replace("'", "''") : dicGrid[key]) + "',";
                            str4 += key + "= '" + ((dicGrid[key].ToLower().Contains("'")) ? dicGrid[key].Replace("'", "''") : dicGrid[key]) + "',";

                        }
                    }
                    str += str1 + System.Environment.NewLine;
                    str += " " + SQLTagEnum.BEGIN + System.Environment.NewLine;
                    str += " " + "SET IDENTITY_INSERT[dbo].[" + tableName + "] ON" + System.Environment.NewLine;
                    str += "  " + SQLTagEnum.INSERT + " " + SQLTagEnum.INTO + " [dbo].[" + tableName + "](" + str2.TrimEnd(',') + ") " + SQLTagEnum.VALUES + " (" + str3.TrimEnd(',') + ")" + System.Environment.NewLine;
                    str += " " + "SET IDENTITY_INSERT [dbo].[" + tableName + "] OFF" + System.Environment.NewLine;
                    str += " " + SQLTagEnum.END + System.Environment.NewLine;
                    str += SQLTagEnum.ELSE + System.Environment.NewLine;
                    str += " " + SQLTagEnum.BEGIN + System.Environment.NewLine;
                    str += "  " + SQLTagEnum.UPDATE + " " + " [dbo].[" + tableName + "] " + SQLTagEnum.SET + " " + str4.TrimEnd(',') + " " + SQLTagEnum.WHERE + " " + PrimaryKey + "=" + priKeyValue + System.Environment.NewLine;
                    str += " " + SQLTagEnum.END + System.Environment.NewLine;
                }
                tmp += str;
            }
            return tmp;
        }

        /// <summary>
        /// 服务器端保存
        /// </summary>
        /// <param name="fileContent"></param>
        /// <param name="sqlfileName"></param>
        private void SaveFileSQL(string fileContent,string sqlfileName)
        {
            string[] sArray = fileContent.Split('!');
            string[] sArrayName = sqlfileName.Split('!');
            int o = 0;
            foreach (string i in sArray)
            {
                string fileName = sArrayName[o];
                //获取程序的基目录。
                string filePath=  System.AppDomain.CurrentDomain.BaseDirectory;
                filePath += "provisionalFile" + "\\";
                fileName += DateTime.Now.ToString("yyyyMMddHHmmss") + ".sql";

                using (FileStream fs = new FileStream(filePath + fileName, FileMode.OpenOrCreate))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.Write(i);
                    }

                }
                o++;

            }
        }


       
    }
}
